﻿#region Usings

using System;
using System.IO;
using System.Net;
using System.Windows.Threading;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Text;

#endregion

namespace ScrumTable.UI.View.CustomControl
{
    /// <summary>
    /// Loads a image Async, while loading a loading gif is show
    /// </summary>
    public class WebAsyncReportImage : WebAsyncImage
    {

        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------
        
        private const string RequestImageMethod = "GET";
        private const int RequestTimeout = 20000; // ms

        private const string ImageBegin = "SRC=\"";
        private const string ImageEnd = "\"";
       
        #endregion
     
        #region Methods

        private string GetImageLocation(string imageWebData)
        {
            string imageLocation = null;

            if (!string.IsNullOrEmpty(imageWebData))
                imageLocation = imageWebData.CutOff(ImageBegin, ImageEnd);
            return imageLocation;
        }

        private void GetImageHtml(Uri toConnect)
        {
            ShowWaitingImage();

            WebRequest request = WebRequest.Create(toConnect);
            request.Credentials = ScrumData.DataContext.ConnectionInformation.NetworkCredentials;
            request.Method = RequestImageMethod;
            request.Timeout = RequestTimeout;
            request.BeginGetResponse(new AsyncCallback(OnLoadImageHtml), request);
        }


        protected override void LoadImageFromUrl(Uri imageUri)
        {
            if (imageUri == null || imageUri == EmptyUri)
            {
                base.LoadImageFromUrl(imageUri);
                return;
            }

            if (imageUri.IsAbsoluteUri)
            {
                GetImageHtml(imageUri);
            }
            else
            {
                base.LoadImageFromUrl(imageUri);
            }
        }

        private void OnLoadImageHtml(IAsyncResult result)
        {
            WebRequest request = (WebRequest)result.AsyncState;
            string webData = null;
            try
            {
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        webData = sr.ReadToEnd();
                    }
                }
                webData = GetImageLocation(webData);
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action<string>)LoadImageHtml ,webData);
            }
            catch (WebException error)
            {
                Logger<WebAsyncImage>.Warn(String.Format(Properties.Resources.LogImageLoadingError, request.RequestUri), error);
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action<string>)LoadImageHtml, null);
            }
        }

        private void LoadImageHtml(string webData)
        {
            if (webData == null)
            {
                base.LoadImageFromUrl(null);
            }
            else
            {
                base.LoadImageFromUrl(new Uri(webData));
            }
        }


        #endregion
 
    }
}
